﻿using System.Collections.Generic;
using System.Linq;
using QSHC.QSchedule.Web.Models;
using QSHC.QSchedule.Web.Services;
using System;
using QSHC.LibrarySL.Ria;
using System.Net;
using System.Xml.Linq;

namespace QSHC.QSchedule.Silverlight.Helpers
{
    public class EmployeeHelper
    {
        public static IEnumerable<Employee> Physicians;
        public static IEnumerable<Employee> Employees;
        public static IEnumerable<XElement> QScheduleAutherization { get; set; }

        public static string LoggedEmployee
        {
            get
            {
                //return WebContext.Current.User.Name.ToUpper();
                return "IT007";
            }
        }

        public static void LoadPhysicians(Action callback)
        {
            var client = new QSHCDomainContext();

            WebClient searchPatientWebClient = new WebClient();
            searchPatientWebClient.DownloadStringCompleted += (sender, args) =>
            {
                var result = XDocument.Parse(args.Result).Element("Physicians").Elements();
                var physicianInactives = new List<string>();
                foreach (var item in result)
                {
                    var a = item.Attribute("Code").Value;
                    physicianInactives.Add(a);
                }

                var lo = client.Load(client.GetPhysiciansQuery());
                lo.Completed += (s, e) =>
                {
                    Physicians = lo.Entities.Where(p => !physicianInactives.Contains(p.EmployeeCode));

                    var lo2 = client.Load(client.GetEmployeesQuery()); //Daeng
                    lo2.Completed += (s2, e2) =>
                    {
                        Employees = lo2.Entities;
                        callback.Invoke();
                    };
                };
            };

            searchPatientWebClient.DownloadStringAsync(new Uri(@"..\XML\QSchedulePhysicianInactive.xml", UriKind.Relative));
        }

        public static void LoadQScheduleAutherization(Action callback)
        {
            WebClient searchPatientWebClient = new WebClient();
            searchPatientWebClient.DownloadStringCompleted += (s, args) =>
            {
                QScheduleAutherization =
                    XDocument.Parse(args.Result).Element("Controls").Elements();

                callback.Invoke();
            };

            searchPatientWebClient.DownloadStringAsync(new Uri(@"..\XML\QScheduleAutherization.xml", UriKind.Relative));
        }

        public static Employee GetPhysician(string physicianCode)
        {
            return Physicians.SingleOrDefault(p => p.EmployeeCode == physicianCode);
        }

        public static Employee GetEmployee(string employeeCode)
        {
            return Employees.Single(p => p.EmployeeCode == employeeCode);
        }
    }
}
